package com.xiukelai.springboot.base;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

public final class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static String getURL(HttpServletRequest request) {
        StringBuffer sb = request.getRequestURL();
        String queryString = request.getQueryString();
        if (queryString != null) {
            return sb.toString() + "?" + queryString;
        }
        return sb.toString();
    }


    /**
     * Get Integer parameter from request. If specified parameter name is not
     * found, the default value will be returned.
     */
    public static int getInt(HttpServletRequest request, String paramName, int defaultValue) {
        String s = request.getParameter(paramName);
        if (s == null || s.equals("")) {
            return defaultValue;
        }
        return Integer.parseInt(s);
    }


    /**
     * Get Integer parameter from request. If specified parameter name is not
     * found, an Exception will be thrown.
     */
    public static int getInt(HttpServletRequest request, String paramName) {
        String s = request.getParameter(paramName);
        return Integer.parseInt(s);
    }


    public static long getLong(HttpServletRequest request, String paramName, long defaultValue) {
        String s = request.getParameter(paramName);
        if (s == null || s.equals("")) {
            return defaultValue;
        }
        return Long.parseLong(s);
    }


    public static long getLong(HttpServletRequest request, String paramName) {
        String s = request.getParameter(paramName);
        return Long.parseLong(s);
    }


    /**
     * Get String parameter from request. If specified parameter name is not
     * found, the default value will be returned.
     */
    public static String getString(HttpServletRequest request, String paramName, String defaultValue) {
        String s = request.getParameter(paramName);
        if (s == null || s.equals("")) {
            return defaultValue;
        }
        return s;
    }


    /**
     * Get String parameter from request. If specified parameter name is not
     * found or empty, an Exception will be thrown.
     */
    public static String getString(HttpServletRequest request, String paramName) {
        String s = request.getParameter(paramName);
        if (s == null || s.equals("")) {
            throw new NullPointerException("Null parameter: " + paramName);
        }
        return s;
    }


    /**
     * Get Boolean parameter from request. If specified parameter name is not
     * found, an Exception will be thrown.
     */
    public static boolean getBoolean(HttpServletRequest request, String paramName) {
        String s = request.getParameter(paramName);
        return Boolean.parseBoolean(s);
    }


    /**
     * Get Boolean parameter from request. If specified parameter name is not
     * found, the default value will be returned.
     */
    public static boolean getBoolean(HttpServletRequest request, String paramName, boolean defaultValue) {
        String s = request.getParameter(paramName);
        if (s == null || s.equals("")) {
            return defaultValue;
        }
        return Boolean.parseBoolean(s);
    }


    /**
     * Get float parameter from request. If specified parameter name is not
     * found, an Exception will be thrown.
     */
    public static float getFloat(HttpServletRequest request, String paramName) {
        String s = request.getParameter(paramName);
        return Float.parseFloat(s);
    }

    public static String htmlEncode(String text) {
        if (text == null || "".equals(text)) {
            return "";
        }
        text = text.replace("<", "&lt;");
        text = text.replace(">", "&gt;");
        text = text.replace(" ", "&nbsp;");
        text = text.replace("\"", "&quot;");
        text = text.replace("\'", "&apos;");
        return text.replace("\n", "<br/>");
    }

    /**
     * 获取客户端IP地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


    /**
     * 获取客户端IP地址
     *
     * @param request
     * @return
     */
    public static String getIPAddress(HttpServletRequest request) {
        // 获取X-Forwarded-For
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            // 获取Proxy-Client-IP
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            // WL-Proxy-Client-IP
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            // 获取的IP实际上是代理服务器的地址，并不是客户端的IP地址
            ip = request.getRemoteAddr();
        }
        /*
         * 如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
         * X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
         * 用户真实IP为： 192.168.1.110
         */
        if (ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /**
     * 探测过滤请求中是否包含当前URL
     *
     * @param request 请求体
     * @param url     URL集合
     * @return 返回包含状态, true包含、false不包含
     */
    public static boolean inContainURL(HttpServletRequest request, List<String> url) {
        boolean result = false;
        StringBuffer reqUrl = request.getRequestURL();
        logger.debug("checkLogin  url : " + reqUrl);
        if (url != null) {
            for (String ignoreUrl : url) {
                if (reqUrl.indexOf(ignoreUrl) > 1) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 探测过滤请求中是否包含当前URL
     *
     * @param request 请求体
     * @param url     参数为以';'分割的URL字符串
     * @return 返回状态, true包含、false不包含
     */
    public static boolean inContainURL(HttpServletRequest request, String url) {
        boolean result = false;
        if (url != null && !"".equals(url.trim())) {
            String[] urlArr = url.split(";");
            StringBuffer reqUrl = request.getRequestURL();
            for (String element : urlArr) {
                if (reqUrl.indexOf(element) > 1) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 获取POST请求中Body参数
     *
     * @param request
     * @return 字符串
     */
    public static String getBodyParm(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bufferedReaderToString(br);
    }

    /**
     * 获取POST请求中Body参数
     *
     * @param serverHttpRequest
     * @return 字符串
     */
    public static String getBodyParm(ServerHttpRequest serverHttpRequest) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(serverHttpRequest.getBody(), "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bufferedReaderToString(br);
    }

    /**
     * 获取POST请求中Body参数
     *
     * @param inputStream
     * @return 字符串
     */
    public static String getBodyParm(InputStream inputStream) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bufferedReaderToString(br);
    }

    private static String bufferedReaderToString(BufferedReader br) {
        String line = null;
        StringBuilder sb = new StringBuilder();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

}
